package com.shure.modules.docs.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shure.modules.docs.entity.Docs;
import com.shure.modules.docs.entity.Files;
import com.shure.modules.docs.entity.Knowledge;
import com.shure.modules.docs.mapper.KnowledgeMapper;
import com.shure.modules.docs.service.DocsService;
import com.shure.modules.docs.service.FilesService;
import com.shure.modules.docs.service.KnowledgeService;

@Service
public class KnowledgeServiceImpl extends ServiceImpl<KnowledgeMapper, Knowledge> implements KnowledgeService {

    private final FilesService filesService;
    private final DocsService docsService;
    private final VectorStore vectorStore;

    public KnowledgeServiceImpl(FilesService filesService, DocsService docsService, RedisVectorStore vectorStore) {
        this.filesService = filesService;
        this.docsService = docsService;
        this.vectorStore = vectorStore;
    }

    @Override
    public void addKbByFile(Long fileId) {
        Files files = filesService.getById(fileId);
        try{
            String content = FileUtils.readFileToString(new File(files.getFilePath()), StandardCharsets.UTF_8);

            List <Document> documents = List.of(new Document(files.getId()+"", content, Map.of("fileName", files.getFileName())));

            vectorStore.add(documents);

        } catch (IOException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addKbByDocs(Long docsId) {
        Docs docs = docsService.getById(docsId);
        String content = docs.getContent();
        List <Document> documents = List.of(new Document(docs.getId()+"", content, Map.of("title", docs.getTitle())));
        vectorStore.add(documents);
    }
    
}
